//
//  LoginViewController.m
//  mhome
//
//  Created by YaSha_Tom on 2018/12/1.
//  Copyright © 2018年 刘春雷. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisteredViewController.h"
#import "NetworkManager.h"
#import "AppDelegate.h"

@interface LoginViewController ()<UITextFieldDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) NSMutableDictionary *parameter;
@end

@implementation LoginViewController

- (NSMutableDictionary *)parameter {
    if(!_parameter){
        _parameter = [NSMutableDictionary dictionary];
    }
    return _parameter;
}

- (LoginView *)loginView {
    if(!_loginView){
        _loginView = [[LoginView alloc]init];
        _loginView.passwordTextField.delegate = self;
        _loginView.accountTextField.delegate = self;
    }
    return _loginView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
    [self.view addSubview:self.loginView];
    @weakify(self);   //解决循环引用问题
    [[_loginView.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self doNetworking];
    }];
    [[_loginView.registeredButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        RegisteredViewController *registeredViewController = [[RegisteredViewController alloc]init];
        [self.navigationController pushViewController:registeredViewController animated:YES];
    }];
    
    [[_loginView.forgetButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        RegisteredViewController *registeredViewController = [[RegisteredViewController alloc]init];
        [self.navigationController pushViewController:registeredViewController animated:YES];
    }];
    [self monitorLogin];
    
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}



# pragma -- 检测密码和用户名是否输入
- (void)monitorLogin {
    @weakify(self)
    //用户名输入监听信号
    RACSignal *validAccountSignal = [_loginView.accountTextField.rac_textSignal map:^id(NSString  *value) {
        @strongify(self);
        [self.parameter setValue:value forKey:@"username"];
        return @(value.length > 0);
    }];
    
    //密码输入监听信号
    RACSignal *validPasswordSignal = [_loginView.passwordTextField.rac_textSignal map:^id(NSString *value) {
        @strongify(self);
        [self.parameter setValue:value forKey:@"password"];
        return @(value.length > 0);
    }];
    RACSignal *loginButtonSignal = [RACSignal combineLatest:@[validAccountSignal, validPasswordSignal] reduce:^id(NSNumber *accountValid, NSNumber *passwordValid) {
        return @([accountValid boolValue] && [passwordValid boolValue]);
    }];
    
    RAC(_loginView.loginButton, backgroundColor) = [loginButtonSignal map:^id(id value) {
        @strongify(self);
        if ([value boolValue]) {
            self.loginView.loginButton.enabled = YES;
            return [UIColor blueColor];
        } else {
            self.loginView.loginButton.enabled = NO;
            return  [UIColor lightGrayColor];
        }
    }];
}

- (void)doNetworking {
    NSString *urlString = [NSString stringWithFormat:@"%@%@",Domain,loginApi];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:self.parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([dic[@"code"] intValue]==0) {
            [QMUITips showInfo:dic[@"msg"] inView:self.view hideAfterDelay:1];
        }else{
            NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
            [de setObject:dic[@"data"][@"id"] forKey:@"userid"];
            [de setBool:YES forKey:@"login"];
            [de setObject:dic[@"data"][@"desStr"] forKey:@"appkey"];
            [de setObject:dic[@"data"][@"mobile"] forKey:@"mobile"];
            [de synchronize];
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate enterTabBarController];
        }
        NSLog(@"========%@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败%@",error);
    }];
}
# pragma -- 点击空白处收起键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_loginView.accountTextField resignFirstResponder];
    [_loginView.passwordTextField resignFirstResponder];
}

- (void)dealloc {
    self.navigationController.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
